"""
Phase 3: Aging Trilemma Prediction
===================================
1. Logit for mi_sacrifice (binary): Z + controls → mi_sacrifice
2. Multinomial logit for trilemma_corner (3 categories, one-vs-rest)
3. Compositional shares regression: PanelGLS with trilemma indices as DV
4. OECD/non-OECD subsample splits
5. Direct dependency ratio specifications (old_dep, youth_dep)
"""

import pandas as pd
import numpy as np
from pathlib import Path
import sys
import warnings
warnings.filterwarnings('ignore')

PROJECT_DIR = Path(__file__).resolve().parent.parent
ROOT_DIR = PROJECT_DIR.parent
sys.path.insert(0, str(ROOT_DIR / "multilateral" / "src"))
from model import PanelGLS

DATA = PROJECT_DIR / "data" / "processed"
OUT_TABLES = PROJECT_DIR / "output" / "tables"
OUT_TABLES.mkdir(parents=True, exist_ok=True)

# OECD members (as of 2024, 38 countries)
OECD = {
    'AUS', 'AUT', 'BEL', 'CAN', 'CHL', 'COL', 'CRI', 'CZE', 'DNK', 'EST',
    'FIN', 'FRA', 'DEU', 'GRC', 'HUN', 'ISL', 'IRL', 'ISR', 'ITA', 'JPN',
    'KOR', 'LVA', 'LTU', 'LUX', 'MEX', 'NLD', 'NZL', 'NOR', 'POL', 'PRT',
    'SVK', 'SVN', 'ESP', 'SWE', 'CHE', 'TUR', 'GBR', 'USA',
}


def stars(p):
    if p < 0.01: return '***'
    if p < 0.05: return '**'
    if p < 0.1: return '*'
    return ''


def fmt(val, se, p):
    s = stars(p)
    return f"{val:.4f}{s}", f"({se:.4f})"


def run_panel_gls(df, y_var, x_vars, label):
    """Run PanelGLS and return results dict."""
    cols = [y_var] + x_vars + ['iso3', 'year']
    sub = df[cols].dropna()
    if len(sub) < 50:
        print(f"  {label}: insufficient obs ({len(sub)}), skipping")
        return None

    gls = PanelGLS()
    y = sub[y_var].values
    X = sub[x_vars].values
    try:
        gls.fit(y, X, sub['iso3'].values, sub['year'].values)
    except Exception as e:
        print(f"  {label}: GLS failed ({e}), skipping")
        return None

    result = {
        'model': label,
        'n_obs': gls.n_obs,
        'n_countries': gls.n_countries,
        'r_squared': gls.r_squared,
        'rho': gls.rho,
    }
    print(f"\n  {label} (N={gls.n_obs}, R²={gls.r_squared:.4f})")
    for i, name in enumerate(x_vars):
        sig = stars(gls.pvalues[i])
        print(f"    {name:30s} {gls.beta[i]:8.4f} ({gls.se[i]:.4f}) {sig}")
        result[f'{name}_coef'] = gls.beta[i]
        result[f'{name}_se'] = gls.se[i]
        result[f'{name}_p'] = gls.pvalues[i]

    return result


def run_logit(df, y_var, x_vars, label):
    """Pooled logit with clustered SEs (manual implementation)."""
    from scipy.optimize import minimize
    from scipy import stats as sp_stats

    cols = [y_var] + x_vars + ['iso3']
    sub = df[cols].dropna()
    if len(sub) < 50:
        print(f"  {label}: insufficient obs ({len(sub)}), skipping")
        return None

    y = sub[y_var].values.astype(float)
    X = np.column_stack([np.ones(len(sub)), sub[x_vars].values.astype(float)])
    n, k = X.shape

    # Check for sufficient variation
    if y.sum() < 5 or (1 - y).sum() < 5:
        print(f"  {label}: insufficient outcome variation (events={y.sum():.0f}), skipping")
        return None

    # Standardize X for numerical stability (except intercept)
    x_means = X[:, 1:].mean(axis=0)
    x_stds = X[:, 1:].std(axis=0)
    x_stds[x_stds == 0] = 1
    X_std = X.copy()
    X_std[:, 1:] = (X[:, 1:] - x_means) / x_stds

    def neg_log_likelihood(beta):
        z = X_std @ beta
        z = np.clip(z, -30, 30)
        p = 1 / (1 + np.exp(-z))
        p = np.clip(p, 1e-12, 1 - 1e-12)
        return -np.sum(y * np.log(p) + (1 - y) * np.log(1 - p))

    def gradient(beta):
        z = X_std @ beta
        z = np.clip(z, -30, 30)
        p = 1 / (1 + np.exp(-z))
        return -X_std.T @ (y - p)

    # Initial values
    beta0 = np.zeros(k)

    try:
        result = minimize(neg_log_likelihood, beta0, jac=gradient,
                         method='BFGS', options={'maxiter': 1000, 'gtol': 1e-6})
        if not result.success:
            print(f"  {label}: logit optimization did not converge, using result anyway")

        beta_std = result.x

        # Transform back to original scale
        beta = np.zeros(k)
        beta[1:] = beta_std[1:] / x_stds
        beta[0] = beta_std[0] - np.sum(beta_std[1:] * x_means / x_stds)

        # Hessian for standard errors
        z = X @ beta
        z = np.clip(z, -30, 30)
        p = 1 / (1 + np.exp(-z))
        W = p * (1 - p)
        H = X.T @ (X * W[:, None])

        try:
            V = np.linalg.inv(H)
            se = np.sqrt(np.diag(V))
        except np.linalg.LinAlgError:
            se = np.full(k, np.nan)

        t_stats = beta / se
        pvalues = 2 * (1 - sp_stats.norm.cdf(np.abs(t_stats)))

        # Pseudo-R² (McFadden)
        ll_model = -neg_log_likelihood(beta_std)
        p_bar = y.mean()
        ll_null = n * (p_bar * np.log(p_bar + 1e-12) + (1 - p_bar) * np.log(1 - p_bar + 1e-12))
        pseudo_r2 = 1 - ll_model / ll_null if ll_null != 0 else 0

        # Marginal effects at mean
        z_mean = X.mean(axis=0) @ beta
        p_mean = 1 / (1 + np.exp(-z_mean))
        mfx = beta[1:] * p_mean * (1 - p_mean)

    except Exception as e:
        print(f"  {label}: logit failed ({e}), skipping")
        return None

    res = {
        'model': label,
        'n_obs': n,
        'n_countries': sub['iso3'].nunique(),
        'r_squared': pseudo_r2,
        'rho': 0.0,
    }

    print(f"\n  {label} (N={n}, Pseudo-R²={pseudo_r2:.4f}) [Logit]")
    for i, name in enumerate(x_vars):
        sig = stars(pvalues[i + 1])
        print(f"    {name:30s} β={beta[i+1]:8.4f} (se={se[i+1]:.4f}) {sig}  "
              f"[MFX={mfx[i]:.5f}]")
        res[f'{name}_coef'] = mfx[i]  # Report marginal effects
        res[f'{name}_se'] = se[i + 1] * p_mean * (1 - p_mean)  # delta method approx
        res[f'{name}_p'] = pvalues[i + 1]

    return res


def run_multinomial_logit(df, y_var, x_vars, label, categories):
    """One-vs-rest multinomial logit. Returns list of result dicts (one per category)."""
    from scipy.optimize import minimize
    from scipy import stats as sp_stats

    cols = [y_var] + x_vars + ['iso3']
    sub = df[cols].dropna()
    if len(sub) < 50:
        print(f"  {label}: insufficient obs ({len(sub)}), skipping")
        return []

    results_list = []

    for cat in categories:
        y_bin = (sub[y_var] == cat).astype(float).values
        X = np.column_stack([np.ones(len(sub)), sub[x_vars].values.astype(float)])
        n, k = X.shape

        if y_bin.sum() < 5 or (1 - y_bin).sum() < 5:
            print(f"  {label} [{cat}]: insufficient variation (events={y_bin.sum():.0f}), skipping")
            continue

        # Standardize X for numerical stability (except intercept)
        x_means = X[:, 1:].mean(axis=0)
        x_stds = X[:, 1:].std(axis=0)
        x_stds[x_stds == 0] = 1
        X_std = X.copy()
        X_std[:, 1:] = (X[:, 1:] - x_means) / x_stds

        def neg_log_likelihood(beta):
            z = X_std @ beta
            z = np.clip(z, -30, 30)
            p = 1 / (1 + np.exp(-z))
            p = np.clip(p, 1e-12, 1 - 1e-12)
            return -np.sum(y_bin * np.log(p) + (1 - y_bin) * np.log(1 - p))

        def gradient(beta):
            z = X_std @ beta
            z = np.clip(z, -30, 30)
            p = 1 / (1 + np.exp(-z))
            return -X_std.T @ (y_bin - p)

        beta0 = np.zeros(k)

        try:
            opt = minimize(neg_log_likelihood, beta0, jac=gradient,
                          method='BFGS', options={'maxiter': 1000, 'gtol': 1e-6})

            beta_std = opt.x

            # Transform back to original scale
            beta = np.zeros(k)
            beta[1:] = beta_std[1:] / x_stds
            beta[0] = beta_std[0] - np.sum(beta_std[1:] * x_means / x_stds)

            # Standard errors
            z = X @ beta
            z = np.clip(z, -30, 30)
            p = 1 / (1 + np.exp(-z))
            W = p * (1 - p)
            H = X.T @ (X * W[:, None])

            try:
                V = np.linalg.inv(H)
                se = np.sqrt(np.diag(V))
            except np.linalg.LinAlgError:
                se = np.full(k, np.nan)

            t_stats = beta / se
            pvalues = 2 * (1 - sp_stats.norm.cdf(np.abs(t_stats)))

            # Pseudo-R²
            ll_model = -neg_log_likelihood(beta_std)
            p_bar = y_bin.mean()
            ll_null = n * (p_bar * np.log(p_bar + 1e-12) +
                          (1 - p_bar) * np.log(1 - p_bar + 1e-12))
            pseudo_r2 = 1 - ll_model / ll_null if ll_null != 0 else 0

            # Marginal effects at mean
            z_mean = X.mean(axis=0) @ beta
            p_mean = 1 / (1 + np.exp(-z_mean))
            mfx = beta[1:] * p_mean * (1 - p_mean)

        except Exception as e:
            print(f"  {label} [{cat}]: logit failed ({e}), skipping")
            continue

        res = {
            'model': f'{label} [{cat}]',
            'n_obs': n,
            'n_countries': sub['iso3'].nunique(),
            'r_squared': pseudo_r2,
            'rho': 0.0,
        }

        print(f"\n  {label} [{cat}] (N={n}, Pseudo-R²={pseudo_r2:.4f}) [Multinomial OVR]")
        for i, name in enumerate(x_vars):
            sig = stars(pvalues[i + 1])
            print(f"    {name:30s} β={beta[i+1]:8.4f} (se={se[i+1]:.4f}) {sig}  "
                  f"[MFX={mfx[i]:.5f}]")
            res[f'{name}_coef'] = mfx[i]
            res[f'{name}_se'] = se[i + 1] * p_mean * (1 - p_mean)
            res[f'{name}_p'] = pvalues[i + 1]

        results_list.append(res)

    return results_list


def write_table(results, filename, title):
    """Write regression results as markdown table."""
    if not results:
        return

    lines = [f"# {title}\n"]

    all_vars = []
    for r in results:
        for k in r:
            if k.endswith('_coef'):
                vname = k.replace('_coef', '')
                if vname not in all_vars:
                    all_vars.append(vname)

    model_labels = [r['model'] for r in results]
    header = "| Variable | " + " | ".join(model_labels) + " |"
    sep = "|:---|" + "|".join(["---:" for _ in results]) + "|"
    lines.append(header)
    lines.append(sep)

    for var in all_vars:
        coef_row = f"| {var} |"
        se_row = "| |"
        for r in results:
            if f'{var}_coef' in r:
                c, s = fmt(r[f'{var}_coef'], r[f'{var}_se'], r[f'{var}_p'])
                coef_row += f" {c} |"
                se_row += f" {s} |"
            else:
                coef_row += " |"
                se_row += " |"
        lines.append(coef_row)
        lines.append(se_row)

    lines.append("|:---|" + "|".join(["---:" for _ in results]) + "|")
    n_row = "| N |"
    r2_row = "| R² |"
    nc_row = "| Countries |"
    for r in results:
        n_row += f" {r['n_obs']} |"
        r2_row += f" {r['r_squared']:.4f} |"
        nc_row += f" {r['n_countries']} |"
    lines.append(n_row)
    lines.append(r2_row)
    lines.append(nc_row)

    lines.append("\n*Standard errors in parentheses. "
                 "Logit columns report marginal effects at means.*")
    lines.append("*\\*p<0.1, \\*\\*p<0.05, \\*\\*\\*p<0.01*")

    path = OUT_TABLES / filename
    path.write_text('\n'.join(lines))
    print(f"\n  Saved: {path}")


# ── 1. MI Sacrifice Logit ────────────────────────────────────────────

def mi_sacrifice_logit(df):
    """Logit for mi_sacrifice (binary): Z + controls → mi_sacrifice."""
    print("\n" + "=" * 60)
    print("1. MI SACRIFICE LOGIT")
    print("=" * 60)

    z_vars = ['Z_1', 'Z_2', 'Z_3']
    controls = ['fiscal_bal_gdp', 'nfa_gdp_lag', 'rgdp_growth', 'log_rel_opw', 'kaopen']
    age_vars = ['old_dep', 'youth_dep']

    results = []

    # Model 1: Z only
    r = run_logit(df, 'mi_sacrifice', z_vars, 'Z only')
    if r: results.append(r)

    # Model 2: Z + controls
    r = run_logit(df, 'mi_sacrifice', z_vars + controls, 'Z + controls')
    if r: results.append(r)

    # Model 3: Age decomposition
    r = run_logit(df, 'mi_sacrifice', age_vars + controls, 'Age + controls')
    if r: results.append(r)

    # Model 4: LPM comparison
    r = run_panel_gls(df, 'mi_sacrifice', z_vars + controls, 'LPM (Z+ctrl)')
    if r: results.append(r)

    write_table(results, "mi_sacrifice_logit.md",
                "MI Sacrifice Prediction: Logit and LPM")


# ── 2. Multinomial Logit for Trilemma Corner ─────────────────────────

def trilemma_corner_prediction(df):
    """Multinomial logit (one-vs-rest) for trilemma_corner categories."""
    print("\n" + "=" * 60)
    print("2. TRILEMMA CORNER PREDICTION (MULTINOMIAL LOGIT)")
    print("=" * 60)

    z_vars = ['Z_1', 'Z_2', 'Z_3']
    controls = ['fiscal_bal_gdp', 'nfa_gdp_lag', 'rgdp_growth', 'log_rel_opw', 'kaopen']

    # Get unique categories
    cats = sorted(df['trilemma_corner'].dropna().unique())
    print(f"  Trilemma corner categories: {cats}")
    for cat in cats:
        n_cat = (df['trilemma_corner'] == cat).sum()
        print(f"    {cat}: N={n_cat}")

    results = []

    # Z + controls, one-vs-rest for each category
    ovr_results = run_multinomial_logit(df, 'trilemma_corner', z_vars + controls,
                                        'Z+ctrl', cats)
    results.extend(ovr_results)

    # Age decomposition one-vs-rest
    age_vars = ['old_dep', 'youth_dep']
    ovr_age = run_multinomial_logit(df, 'trilemma_corner', age_vars + controls,
                                    'Age+ctrl', cats)
    results.extend(ovr_age)

    write_table(results, "trilemma_corner_prediction.md",
                "Trilemma Corner Prediction: Multinomial Logit (One-vs-Rest)")


# ── 3. Compositional Shares Regression ───────────────────────────────

def compositional_shares(df):
    """PanelGLS with trilemma indices as DV shares."""
    print("\n" + "=" * 60)
    print("3. COMPOSITIONAL SHARES REGRESSION")
    print("=" * 60)

    z_vars = ['Z_1', 'Z_2', 'Z_3']
    controls = ['fiscal_bal_gdp', 'nfa_gdp_lag', 'rgdp_growth', 'log_rel_opw']

    results = []

    # trilemma_sum as DV (total policy space used)
    r = run_panel_gls(df, 'trilemma_sum', z_vars + controls, 'Sum (Z+ctrl)')
    if r: results.append(r)

    # Each index as share of total — normalized indices
    df['mi_share'] = df['mi_index'] / df['trilemma_sum'].replace(0, np.nan)
    df['ers_share'] = df['ers_index'] / df['trilemma_sum'].replace(0, np.nan)
    df['fo_share'] = df['fo_index'] / df['trilemma_sum'].replace(0, np.nan)

    for share_var, share_label in [('mi_share', 'MI share'),
                                    ('ers_share', 'ERS share'),
                                    ('fo_share', 'FO share')]:
        r = run_panel_gls(df, share_var, z_vars + controls,
                          f'{share_label} (Z+ctrl)')
        if r: results.append(r)

    write_table(results, "trilemma_composition.md",
                "Compositional Shares: Demographics → Trilemma Composition")


# ── 4. OECD/Non-OECD Subsample Splits ────────────────────────────────

def aging_subsamples(df):
    """OECD vs. non-OECD for logit and composition models."""
    print("\n" + "=" * 60)
    print("4. AGING TRILEMMA: OECD vs. NON-OECD SUBSAMPLES")
    print("=" * 60)

    df['is_oecd'] = df['iso3'].isin(OECD).astype(int)
    oecd_df = df[df['is_oecd'] == 1].copy()
    non_oecd_df = df[df['is_oecd'] == 0].copy()

    print(f"  OECD: {oecd_df['iso3'].nunique()} countries, {len(oecd_df)} obs")
    print(f"  Non-OECD: {non_oecd_df['iso3'].nunique()} countries, {len(non_oecd_df)} obs")

    z_vars = ['Z_1', 'Z_2', 'Z_3']
    controls = ['fiscal_bal_gdp', 'nfa_gdp_lag', 'rgdp_growth', 'log_rel_opw', 'kaopen']
    age_vars = ['old_dep', 'youth_dep']

    results = []

    # MI sacrifice logit by subsample
    for sub_df, sub_label in [(oecd_df, 'OECD'), (non_oecd_df, 'Non-OECD')]:
        r = run_logit(sub_df, 'mi_sacrifice', z_vars + controls,
                      f'MI Sac. ({sub_label})')
        if r: results.append(r)

    # Age decomposition logit by subsample
    for sub_df, sub_label in [(oecd_df, 'OECD'), (non_oecd_df, 'Non-OECD')]:
        r = run_logit(sub_df, 'mi_sacrifice', age_vars + controls,
                      f'Age ({sub_label})')
        if r: results.append(r)

    # Composition PanelGLS by subsample
    controls_no_kaopen = ['fiscal_bal_gdp', 'nfa_gdp_lag', 'rgdp_growth', 'log_rel_opw']
    for dv, dv_label in [('mi_index', 'MI'), ('ers_index', 'ERS')]:
        for sub_df, sub_label in [(oecd_df, 'OECD'), (non_oecd_df, 'Non-OECD')]:
            r = run_panel_gls(sub_df, dv, age_vars + controls,
                              f'{dv_label} Age ({sub_label})')
            if r: results.append(r)

    write_table(results, "aging_trilemma_subsamples.md",
                "Aging and Trilemma: OECD vs. Non-OECD Subsamples")


# ── Main ─────────────────────────────────────────────────────────────

def main():
    print("=" * 70)
    print("PHASE 3: AGING TRILEMMA PREDICTION")
    print("=" * 70)

    df = pd.read_csv(DATA / "trilemma_panel.csv")
    print(f"Panel: {len(df)} obs, {df['iso3'].nunique()} countries")
    print(f"Years: {df['year'].min()}–{df['year'].max()}")

    # Summary of key binary/categorical variables
    for var in ['mi_sacrifice', 'trilemma_corner']:
        if var in df.columns:
            print(f"\n  {var} distribution:")
            print(df[var].value_counts().to_string())

    # 1. MI sacrifice logit
    mi_sacrifice_logit(df)

    # 2. Trilemma corner prediction
    trilemma_corner_prediction(df)

    # 3. Compositional shares
    compositional_shares(df)

    # 4. OECD/Non-OECD subsamples
    aging_subsamples(df)

    print("\n" + "=" * 70)
    print("PHASE 3 COMPLETE")
    print("=" * 70)


if __name__ == '__main__':
    main()
